package org.argeproje.resim.proc.histogram;
import java.util.ArrayList;
import java.util.Iterator;

import org.argeproje.resim.proc.Processor;
import org.argeproje.resim.proc.data.*;
/*
Definition
  Performs local histogram equalization on image. 
Inputs
  ImageDA
Parameters
  wxh: Width and height of local image segment around pixel on which local histogram
  equalization algorithm is run.
Outputs
  ImageDA
 */
public class LocalHistogramEqualizePR extends Processor {
	private int _localWidth = 3;
	private int _localHeight = 3;
	public void setParameters(int localWidth, int localHeight){
		setParamLocalWidth(localWidth);
		setParamLocalHeight(localHeight);
	}
	public void setParamLocalWidth(int localWidth){
		_localWidth = localWidth;
	}
	public int getParamLocalWidth(){
		return _localWidth;
	}
	public void setParamLocalHeight(int localHeight){
		_localHeight = localHeight;
	}
	public int getParamLocalHeight(){
		return _localHeight;
	}
	public Data process() {
		ImageDA im = getInputAsImageDA();   
	    int nBand = im.getNBands();
	    ArrayList<ImageSegmentDA> segments = new ArrayList<ImageSegmentDA>();
	    int segmentSize = _localWidth * _localHeight;
	    int centerX = (_localWidth - 1) / 2;
	    int centerY = (_localHeight - 1) / 2;
	    for (int i = 0; i < nBand; i++) {
	    	int maxPixelVal = im.getNBins(i) - 1;
			ImageSegmentDA segment = new ImageSegmentDA(im, i, _localWidth, _localHeight, 0, 0);
			while(segment.get1PixelNextSegment() != null){
				segments.add(segment);
				float[][] pixelArray = segment.getSegmentData();
				float centerPixel = pixelArray[centerX][centerY];
				int sum = 0;
				for (int j = 0; j < _localWidth; j++) {
					for (int k = 0; k < _localHeight; k++) {
						if(centerPixel >= pixelArray[j][k]){
							sum = sum + 1;
						}
					}
				}
				
				float result = (float) ((float)sum / segmentSize * maxPixelVal);                
				pixelArray[centerX][centerY] = result;
				segment = segment.get1PixelNextSegment();
			}
		}
	    for (Iterator iterator = segments.iterator(); iterator.hasNext();) {
			ImageSegmentDA imageSegmentDA = (ImageSegmentDA) iterator.next();
			imageSegmentDA.writePixel(centerX, centerY);
		}
	    setOutput(new ImageDA(im));
		return getOutput();
	}
}
